import store from '@/store'

let platform = ''
// #ifdef APP-PLUS
platform = 'app';
// #endif
// #ifdef MP-WEIXIN
platform = 'weixin';
// #endif
// #ifdef MP-KUAISHOU
platform = 'kuaishou';
// #endif
// #ifdef H5
platform = 'h5';
// #endif
const nodeEnv = process.env.NODE_ENV
console.log(platform);
// 统一请求

  let app = {}
  // #ifdef MP-WEIXIN
  app = getApp({
    allowDefault: true
  }).$vm
  // #endif
  // #ifndef MP-WEIXIN
  app = getApp({
    allowDefault: true
  })
  // #endif

import config from "./config.js";
const objKeySort = function (arys) { 
 	 //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获	取的属性名进行排序，newkey是一个数组
     var newkey = Object.keys(arys).sort();　　 
     //console.log('newkey='+newkey);
     var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
     for(var i = 0; i < newkey.length; i++) {//遍历newkey数组
         newObj[newkey[i]] = arys[newkey[i]];  //向新创建的对象中按照排好的顺序依次增加键值对   
     }
     return newObj; //返回排好序的新对象
 }
const instance = async (url, options) => {
	let baseURL = config.webUrl;
	if (url.indexOf('http') === -1) url = baseURL + url
	let header = {
		//'Content-Type': 'application/json; charset=UTF-8',
		'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
	}
	//if (channel) header.Channel = channel 
	if (options.header) header = {...header, ...options.header}
	options.method = options.method || 'GET'
	if (options.method == 'POST') {
		
	}
	let params = options.data;
	params.deviceid = config.deviceid
	params._channel = config.channel
	params._platform = config.platform
	
	
	let _token = uni.getStorageSync("token")
	if(_token){
		params.token = _token;
	}
	
	let _inviter_uid = uni.getStorageSync("INVITER_UID")
	if(_inviter_uid){
		params._inviter_uid = _inviter_uid;
	}
	
	console.log(params)
	//console.time('time'); 
	let beginTime = +new Date();
	let [error, res] = await uni.request({
		url: url,
		header: header,
		method: options.method,
		data: params,
		//formData:options.data,
	})
	let endTime = +new Date();
	console.log(url+"用时:"+(endTime-beginTime)+"ms");
	//console.timeEnd('time');
	if(error){
		console.log("error",error)
		uni.showToast({
			icon:"none",
		    title:"网络连接失败",
		});
		error.url = url
		//uni.$utils.sendErroLog(error);
	}
	//if (options.method == 'POST') {
		uni.hideLoading();
	//}
	
	if(res.data.code == 0){
		uni.showToast({
			icon:"none",
		    title:res.data.msg,
		});		
	}
	return res
}
const onError = (res)=>{
	
	console.log("接收到错误",res)
	if(res.data.err=='jump'){
		uni.hideLoading();
		if(res.data.msg&&res.data.msg!=''){
			uni.showModal({
				title: '提示',
				content: res.data.msg,
				showCancel: false,
				confirmText:"好的",
				success: function(res) {
					uni.navigateTo({
						url: res.data.path,
						animationType: "fade-in"
					});
				}
			});
		}else{
			uni.navigateTo({
				url: res.data.path,
				animationType: "fade-in"
			});
		}
		return;
	}
	if(res.data.msg){
		uni.showToast({
			icon:"none",
		    title:res.data.msg,
		});		
	}else{
		uni.showToast({
			icon:"none",
		    title:"请求错误",
		});	
	}
							
		
		
}
const http = {
	get: async (url, params, config) => {
		let options = {};
		if (typeof config === 'undefined') config ={}
		options = {...options, ...config}
		options.data = params;
		options.method = 'GET';
		// 解决nvue不渲染问题
		return await new Promise((resolve, reject) => {
			instance(url, options).then((res) => {
					//if(process.env.NODE_ENV === 'development'){
						console.log("接口",url)
						console.log("参数",params)
						//console.log("返回", JSON.stringify(res, null, 2).replace(/&/g, '&') .replace(/</g, '<').replace(/>/g, '>'))
						console.log("返回", res)
					//}
					
					if(res.statusCode == 401){
						uni.setStorageSync("token","")
						//uni.navigateTo({url:"/pages/login/login"})
						uni.checkUserLogin()
						reject()
					}
					
					if(res.statusCode==200){
						if(res.data.err){
							onError(res)
							reject()
						}
						if(res.data.code == 0){
							onError(res)
							reject()
						}
						setTimeout(() => {
							resolve(res.data)
						}, 1)
					}else{
						if(process.env.NODE_ENV === 'development'){ 
							console.log('开发环境',res)
							let err = res.data;
							console.log(err.line)
							uni.showModal({
								title: '错误提示',
								showCancel:false,
								content: `${err.msg}\n${err.file || ""}\n在第${err.line ||0}行`
							});	
							/* uni.setStorageSync('err_msg',res.data)
							uni.navigateTo({
								url: '/pages/err/err_msg',
							}); */
						}else{
							uni.showToast({
								icon:"none",
							    title:"服务器开了一点小差，请重试",
							});	
						}
						
						reject()
					}
				}).catch((err)=>{
					console.log("err".err)
				})
		})
		// return await instance(url, options);
	},
	post: async (url,params) => {
		let options = {};
			//JSON.stringify(params);
			//console.log(JSON.stringify(params))
			//params.data = params;
			options.data = params; 
			options.method = 'POST';
			return await new Promise((resolve, reject) => {
				instance(url, options).then((res) => {
					//if(process.env.NODE_ENV === 'development'){
						console.log("接口",url)
						console.log("参数",params)
						//console.log("返回", JSON.stringify(res, null, 2).replace(/&/g, '&') .replace(/</g, '<').replace(/>/g, '>')) 
						console.log("返回", res)
					//}
					
					if(res.statusCode==200){
						if(res.data.err){
							onError(res)
							reject()
						}
						
						if(res.data.code == 0){
							onError(res)
							reject()
						}
						
						setTimeout(() => {
							resolve(res.data)
						}, 1)
					}
					else if(res.statusCode == 401){
						uni.setStorageSync("token","")
						//uni.navigateTo({url:"/pages/login/login"})
						uni.checkUserLogin()
						reject()
					}
					else{
						console.log("接收到错误:err_msg",res)
						if(process.env.NODE_ENV === 'development'){ 
							console.log('开发环境') 
							let err = res.data;
							console.log(err.line)
							uni.showModal({
								title: '错误提示',
								showCancel:false,
								content: `${err.msg}\n${err.file}\n在第${err.line}行`
							});
						}else{
							uni.showToast({
								icon:"none",
							    title:"服务器开了一点小差，请重试",
							});	
						}
						
						reject()
					}
				})
				.catch((err)=>{
					console.log("err".err)
				})
			})
	},
	uniCloud:async (fn,params) => {
		return await new Promise((resolve, reject) => {
					uniCloud.callFunction({
						name: fn,
						data: params,
						success: (e) => {
							resolve(e)
						},
						fail: (error) => {
							reject(error)
						}
					})
			})
	},
	upload_v1: async(action,params,localPath) =>{
		let url = '';
		let options = {};
		let key = "5cZSnCiaWDFPftYRnjzepA8CzDE2yEBX";
		let timestamp = new Date().getTime();
		params.token = uni.getStorageSync('login@token') || '';
		let sign =  md5(action+timestamp+JSON.stringify(params)+key).toUpperCase(); 
			params.data = JSON.stringify(params);
			params.sign = sign;
			params.action = action;
			params.timestamp = timestamp;
			if (typeof params !== 'undefined') options.data = params; 
			options.method = 'POST';
			let baseURL = 'http://farm.ymatong.com/api'
			baseURL +=("/"+action);
			let header = {
				//'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
			}
			//console.log(params)
			let [error, res] = await uni.uploadFile({
			    url: "http://farm.ymatong.com/api",
			    filePath: localPath[0],
			    name: 'imgs',
			    formData: params,
			});
			res.data = JSON.parse(res.data);
			return res;
	},
	upload: async (path,params,localPath) => {
		params = params||{}
		params.token = uni.getStorageSync("token")
		console.log(localPath)
		return await new Promise((resolve, reject) => {
			 uni.uploadFile({
				url: config.webUrl + path +'?token='+uni.getStorageSync("token"), //仅为示例，非真实的接口地址
				//url: "http://chuwu.5gtc.net" + path +'?token='+uni.getStorageSync("token"), //仅为示例，非真实的接口地址		
				filePath: localPath,
				name: "file",
				dataType:"json",
				formData: params,
				success: (res) => {
					console.log("upload res",res)
					let data = JSON.parse(res.data)
					if(data.code == 0){
						uni.showToast({
							icon:"none",
						    title:data.msg,
						});	
						reject()
					}
					if(data.code == 401){
						uni.showToast({
							icon:"none",
						    title:data.msg,
						});
						uni.setStorageSync("token","")
						//uni.navigateTo({url:"/pages/login/login"})
						/pages/login/login
						reject()
					}
					if(data.code == 500){
						reject()
					}
					console.log(data)
					resolve(data)
				},
				 fail: (err) => {
					console.log("upload err",err) 
				    reject(err)
				},
				complete(res) {
					uni.hideLoading();
					//console.log(res)
				}
			});
		});
	/* 	let url = '';
		let options = {};
		let key = "5cZSnCiaWDFPftYRnjzepA8CzDE2yEBX";
		let timestamp = new Date().getTime();
		params.token = uni.getStorageSync('login@token') || '';
		let sign =  md5(action+timestamp+JSON.stringify(params)+key).toUpperCase(); 
			params.data = JSON.stringify(params);
			params.sign = sign;
			params.action = action;
			params.timestamp = timestamp;
			if (typeof params !== 'undefined') options.data = params; 
			options.method = 'POST';
			let baseURL = 'http://farm.ymatong.com/api'
			baseURL +=("/"+action);
			let header = {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
			}
			const uploadTask = uni.uploadFile({
			      url : baseURL,
			      filePath: localPath,
				  header: header,
			      name: 'imgs',
			      formData:params,
			      success: function (uploadFileRes) {
			       console.log(uploadFileRes.data);
			      }
			     });
			
			return uploadTask; */
			/* return await new Promise((resolve, reject) => {
				instance(url, options).then((res) => {
					setTimeout(() => {
						resolve(res)
					}, 1)
				})
			}) */
		// return await instance(url, options);
	},
	

	
/* 	post: async (url, params) => {
		let options = {};
		if (typeof params !== 'undefined') options.data = params;
		options.method = 'POST';
		return await new Promise((resolve, reject) => {
			instance(url, options).then((res) => {
				setTimeout(() => {
					resolve(res)
				}, 1)
			})
		})
	}, */
	
	delete: async (url, params) => {
		let options = {};
		if (typeof params !== 'undefined') options.data = params;
		options.method = 'DELETE';
		return await new Promise((resolve, reject) => {
			instance(url, options).then((res) => {
				setTimeout(() => {
					resolve(res)
				}, 1)
			})
		})
		// return await instance(url, options);
	},
}
module.exports = http
